<template>
  <!-- 搜索 -->
  <ContentWrap>
    <el-form ref="queryFormRef" class="-mb-15px" :model="queryParams">
      <el-row :gutter="20">
        <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="4">
          <el-form-item label="订单来源" prop="source">
            <el-select
              v-model="queryParams.source"
              clearable
              placeholder="全部"
              @change="handleSourceChange"
            >
              <el-option
                v-for="dict in sourceList"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="4" v-if="queryParams.source">
          <el-form-item label="销售门店" prop="tenantIds">
            <template #label>
              销售{{
                sourceList.find((item) => {
                  return item.value == queryParams.source
                })?.label
              }}
            </template>
            <el-select v-model="queryParams.tenantIds" clearable multiple placeholder="全部">
              <el-option
                v-for="item in tenantList"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="4">
          <el-form-item label="申请员工" prop="employeeName">
            <el-select v-model="queryParams.employeeName" clearable placeholder="全部">
              <el-option
                v-for="item in employeeList"
                :key="item.employeeId"
                :label="item.employeeName"
                :value="item.employeeId"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="4">
          <el-form-item label="商品名称" prop="spuName">
            <el-input
              v-model="queryParams.spuName"
              clearable
              placeholder="请输入商品 SPU 名称"
              @keyup.enter="handleQuery"
            />
          </el-form-item>
        </el-col>
        <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="4">
          <el-form-item label="退款编号" prop="no">
            <el-input
              v-model="queryParams.no"
              clearable
              placeholder="请输入退款编号"
              @keyup.enter="handleQuery"
            />
          </el-form-item>
        </el-col>
        <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="4">
          <el-form-item label="销售订单" prop="orderNo">
            <el-input
              v-model="queryParams.orderNo"
              clearable
              placeholder="请输入订单编号"
              @keyup.enter="handleQuery"
            />
          </el-form-item>
        </el-col>
        <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="4">
          <el-form-item label="售后状态" prop="status">
            <el-select v-model="queryParams.status" clearable placeholder="请选择售后状态">
              <el-option label="全部" value="0" />
              <el-option
                v-for="dict in getDictOptions(DICT_TYPE.TRADE_AFTER_SALE_STATUS)"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="4">
          <el-form-item label="售后方式" prop="way">
            <el-select v-model="queryParams.way" clearable placeholder="请选择售后方式">
              <el-option
                v-for="dict in getDictOptions(DICT_TYPE.TRADE_AFTER_SALE_WAY)"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="4">
          <el-form-item label="售后类型" prop="type">
            <el-select v-model="queryParams.type" clearable placeholder="请选择售后类型">
              <el-option
                v-for="dict in getDictOptions(DICT_TYPE.TRADE_AFTER_SALE_TYPE)"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="4">
          <el-form-item label="创建时间" prop="createTime">
            <el-date-picker
              v-model="queryParams.createTime"
              :shortcuts="defaultShortcuts"
              :default-time="[new Date('1 00:00:00'), new Date('1 23:59:59')]"
              end-placeholder="自定义时间"
              start-placeholder="自定义时间"
              type="daterange"
              value-format="YYYY-MM-DD HH:mm:ss"
            />
          </el-form-item>
        </el-col>
        <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="4">
          <el-form-item>
            <el-button @click="handleQuery">
              <Icon class="mr-5px" icon="ep:search" />
              搜索
            </el-button>
            <el-button @click="resetQuery">
              <Icon class="mr-5px" icon="ep:refresh" />
              重置
            </el-button>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
  </ContentWrap>
  <!-- 统计卡片 -->
  <el-row :gutter="10" class="summary">
    <el-col :span="8" v-loading="loading">
      <SummaryCard
        title="订单数量"
        icon="icon-park-outline:transaction-order"
        icon-color="bg-blue-100"
        icon-bg-color="text-blue-500"
        :value="summary?.orderCount || 0"
      />
    </el-col>

    <el-col :span="8" v-loading="loading">
      <SummaryCard
        title="退款金额"
        icon="ri:refund-2-line"
        icon-color="bg-green-100"
        icon-bg-color="text-green-500"
        prefix="￥"
        :decimals="2"
        :value="Number(fenToYuan(summary?.afterSalePrice || 0))"
      />
    </el-col>
    <el-col :span="8" v-loading="loading">
      <SummaryCard
        title="会员数量"
        icon="heroicons:receipt-refund"
        icon-color="bg-yellow-100"
        icon-bg-color="text-yellow-500"
        :value="summary?.afterSaleCount || 0"
      />
    </el-col>
  </el-row>
  <ContentWrap>
    <el-tabs v-model="queryParams.status" @tab-click="tabClick">
      <el-tab-pane
        v-for="item in statusTabs"
        :key="item.label"
        :label="item.label"
        :name="item.value"
      />
    </el-tabs>
    <!-- 列表 -->
    <el-table
      v-loading="loading"
      :data="list"
      row-key="id"
      :cell-style="{ padding: 0, borderBottom: 'none' }"
      :header-cell-style="{ padding: 0 }"
      :row-class-name="'table-row-class'"
    >
      <OrderTableColumn :list="list">
        <template #default="{ row }">
          <div class="flex items-center justify-center">
            <el-button v-if="row.status == 50" disabled link type="success">已退款</el-button>
            <el-button v-else link type="primary" @click="openAfterSaleDetail(row.id)"
              >处理退款</el-button
            >
          </div>
        </template>
      </OrderTableColumn>
      <template #empty>
        <Empty />
      </template>
    </el-table>
    <!-- 分页 -->
    <Pagination
      v-model:limit="queryParams.pageSize"
      v-model:page="queryParams.pageNo"
      :total="total"
      @pagination="getList"
    />
  </ContentWrap>
</template>
<script lang="ts" setup>
import * as TradeOrderApi from '@/api/mall/trade/order'

import * as AfterSaleApi from '@/api/mall/trade/afterSale/index'
import { DICT_TYPE, getDictOptions } from '@/utils/dict'
import { TabsPaneContext } from 'element-plus'
import { cloneDeep } from 'lodash-es'
import { OrderTableColumn } from './components'
import { fenToYuan } from '@/utils'
import { defaultShortcuts } from '@/utils/formatTime'

defineOptions({ name: 'TradeAfterSale' })

const { push } = useRouter() // 路由跳转

const loading = ref(true) // 列表的加载中
const total = ref(0) // 列表的总页数
const list = ref<AfterSaleApi.TradeAfterSaleVO[]>([]) // 列表的数据
const statusTabs = ref([
  {
    label: '全部',
    value: '0'
  }
])
const queryFormRef = ref() // 搜索的表单
// 查询参数
const queryParams = reactive<any>({
  pageNo: 1,
  pageSize: 10,
  no: null,
  status: '0',
  orderNo: null,
  spuName: null,
  createTime: [],
  way: null,
  type: null,
  source: undefined, //订单来源
  tenantIds: undefined, //销售门店
  employeeName: undefined //销售员工
})
// 交易订单来源
const sourceList = ref([
  {
    label: '门店',
    value: 4
  },
  {
    label: '商城',
    value: 5
  }
])

// 销售员工选择列表
import * as UserApi from '@/api/shop/system/user/index'

const employeeList = ref<any>([])
const getEmployeeList = async () => {
  const data = await UserApi.getEmployeeList()
  employeeList.value = data
}
// 订单统计数据
const summary = ref<TradeOrderApi.TradeOrderSummaryRespVO>()
/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const data = cloneDeep(queryParams)
    // 处理掉全部的状态，不传就是全部
    if (data.status === '0') {
      delete data.status
    }
    // 统计
    summary.value = await TradeOrderApi.getOrderSummary(unref(queryParams))
    // 执行查询
    const res = await AfterSaleApi.getAfterSalePage(data)
    list.value = res.list as AfterSaleApi.TradeAfterSaleVO[]
    total.value = res.total
  } finally {
    loading.value = false
  }
}
/** 搜索按钮操作 */
const handleQuery = async () => {
  queryParams.pageNo = 1
  await getList()
}
/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields()
  handleQuery()
}
/** tab 切换 */
const tabClick = async (tab: TabsPaneContext) => {
  nextTick(async () => {
    queryParams.status = tab.paneName
    await getList()
  })
}

/** 处理退款 */
const openAfterSaleDetail = (id: number) => {
  push({ name: 'TradeAfterSaleDetail', params: { id } })
}
// 销售门店或商城 选择列表
import * as TenantApi from '@/api/system/tenant'
const tenantList = ref<any>([])
const handleSourceChange = async () => {
  queryParams.tenantIds = undefined
  tenantList.value = []
  if (queryParams.source) {
    let params = {
      tenantType: queryParams.source
    }
    const data = await TenantApi.getChildTenantWithPostList(params)

    data.map((ele) => {
      tenantList.value.push({
        name: ele.name,
        id: ele.id
      })
    })
  }
}
onMounted(async () => {
  await getList()
  await getEmployeeList()
  // 设置 statuses 过滤
  for (const dict of getDictOptions(DICT_TYPE.TRADE_AFTER_SALE_STATUS)) {
    statusTabs.value.push({
      label: dict.label,
      value: dict.value
    })
  }
})
</script>
<style lang="scss" scoped>
:deep(.order-table-col > .cell) {
  padding: 0;
}
:deep(.table-row-class) {
  --el-table-row-hover-bg-color: transparent;
}
.summary {
  .el-col {
    margin-bottom: 10px;
  }
}
</style>
